using System;
using System.Linq;

namespace CodeDom
{
  public class TemplateField : ItemProxy
  {
    private Template _owner;
    private string _type;
    static private readonly Guid TEMPLATEFIELD_TEMPLATEID = new Guid("{455A3E98-A627-4B40-8035-E683A0331AC7}");

    static private readonly Guid TEMPLATEFIELD_TYPE_FIELDID = new Guid("{AB162CC0-DC80-4ABF-8871-998EE5D7BA32}");

    public TemplateField(Item item) : base(item)
    {
      Field typeField = item.GetField(TEMPLATEFIELD_TYPE_FIELDID);
      if (typeField != null)
        _type = typeField.Value;
    }

    public Template Owner
    {
      get { 
        if (_owner == null)
        {
          Item ownerTemplate = Item.Parent.Parent;
          if (Template.IsValid(ownerTemplate))
            _owner = Item.Connection.GetTemplate(ownerTemplate.ID);
        }
        return _owner; 
      }
    }

    public string Type
    {
      get { return _type; }
    }

    static public bool IsValid(IItem item)
    {
      return (item.TemplateID == TEMPLATEFIELD_TEMPLATEID);
    }
  }
}